package com.zookeeper.lock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by Administrator on 2016/12/26 0026.
 */
public class ZooKeeperLockFactory {

    private static ZooKeeperLockConfig zooKeeperLockConfig;

    private static void initProperties() throws IOException {
        if(zooKeeperLockConfig == null) {
            ZooKeeperLockConfig zooKeeperLockConfig = new ZooKeeperLockConfig();
            Properties properties = new Properties();
            properties.load(ZooKeeperUtils.class.getResourceAsStream("/zookeeper.lock.properties"));

            String host = properties.getProperty("zookeeper.lock.host");
            zooKeeperLockConfig.setHost(host);

            String port = properties.getProperty("zookeeper.lock.port");
            zooKeeperLockConfig.setPort(Integer.parseInt(port));

            String minWaitMillis = properties.getProperty("zookeeper.min.wait.millis");
            String maxWaitMillis = properties.getProperty("zookeeper.max.wait.millis");
            if(minWaitMillis != null) {
                zooKeeperLockConfig.setMinWaitMillis(Long.parseLong(minWaitMillis));
            }
            if(maxWaitMillis != null) {
                zooKeeperLockConfig.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
            }

            String rootPath = properties.getProperty("zookeeper.lock.root.path");
            if(rootPath != null) {
                zooKeeperLockConfig.setRootPath(rootPath);
            }

            String sessionTimeout = properties.getProperty("zookeeper.lock.session.timeout");
            if(sessionTimeout != null) {
                zooKeeperLockConfig.setSessionTimeout(Integer.parseInt(sessionTimeout));
            }
            ZooKeeperLockFactory.zooKeeperLockConfig = zooKeeperLockConfig;
        }
    }

    private static void createRootPathIfNotExists() {
        try {
            initProperties();
            ZooKeeperLockWatcher initLockWatcher = new ZooKeeperLockWatcher();
            ZooKeeper initZooKeeper = ZooKeeperUtils.getZooKeeper(zooKeeperLockConfig.getConnectString(), 3000, initLockWatcher);
            initLockWatcher.awaitSyncConnected(3000);
            if(initZooKeeper.exists(zooKeeperLockConfig.getRootPath(), false) == null) {
                initZooKeeper.create(zooKeeperLockConfig.getRootPath(), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            initZooKeeper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static {
        createRootPathIfNotExists();
    }

    public static ZooKeeperLock getZooKeeperLock(int timeout) {
        return new ZooKeeperLock(zooKeeperLockConfig, timeout);
    }

    public static ZooKeeperLock getZooKeeperLock(String group, int timeout) {
        return new ZooKeeperLock(zooKeeperLockConfig, group, timeout);
    }
}
